package com.yequan.mq.service;

import com.yequan.exe.core.ExeExecutor;
import com.yequan.mq.config.Properties;
import com.yequan.pojo.BaseCalcInfo;
import com.yequan.mq.listener.ExeMqMessageListener;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.exception.MQClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

/**
 * @author yq
 * @date 2020/08/31
 */
@Service
public class ExeConsumerService {

    private DefaultMQPushConsumer consumer = null;

    @Resource(name = "exeExecutor")
    private ExeExecutor exeExecutor;

    @Autowired
    private Properties appProperties;

    @PostConstruct
    public void initMQConsumer() {
        consumer = new DefaultMQPushConsumer("exeGroup");
        consumer.setNamesrvAddr("127.0.0.1:9876");
        try {
            consumer.subscribe("exe-topic", "*");
            consumer.registerMessageListener(new ExeMqMessageListener(exeExecutor, combineBaseCalcInfo()));
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    @PreDestroy
    public void shutDownConsumer() {
        if (consumer != null) {
            consumer.shutdown();
        }
    }

    private BaseCalcInfo combineBaseCalcInfo() {
        BaseCalcInfo baseCalcInfo = new BaseCalcInfo();
        baseCalcInfo.setExeRootPath(appProperties.getExeRootPath())
                .setFileRootPath(appProperties.getFileRootPath())
                .setHost(appProperties.getHost())
                .setUsername(appProperties.getUsername())
                .setPassword(appProperties.getPassword())
                .setPort(appProperties.getPort());
        return baseCalcInfo;
    }

}
